<?php

namespace api\controller;

use common\controller\VerifyController;
use common\exception\LogicException;
use common\service\ProducerManageHistoryService;
use common\service\ProducerManageService;
use common\service\TaskWorkOrderService;
use common\service\TenantService;
use common\validate\ProducerManage;
use support\EntityTaskFilterParser;
use support\ErrorCode;
use think\Exception;
use think\Request;
use think\Response;

class ProducerManageController extends VerifyController
{
    /**
     * @var
     */
    protected $producerManageService;

    public function __construct()
    {
        parent::__construct();
        $this->producerManageService = ProducerManageService::getInstance();
    }

    /**
     * 获取环节周期时间
     * @param Request $request
     * @return Response
     */
    public function getSegmentCycleTime(Request $request)
    {
        $param = $request->param();
        try {
            $take = $param['param']['take'] ?? 'all';
            $resData = $this->producerManageService->getSegmentCycleTime($param['param'], $take);
            if ($take == 'all') {
                return json($resData);
            } else {
                return json(success_response('', $resData));
            }
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取环节任务列表
     * @param Request $request
     * @return Response
     */
    public function getSegmentTaskList(Request $request)
    {
        $param = $request->param();
        try {
            $resData = $this->producerManageService->getSegmentTaskList($param['param']);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取环节任务详情列表
     * @param Request $request
     * @return Response
     */
    public function getSegmentTaskDetailList(Request $request)
    {
        $param = $request->param();
        try {
            $resData = $this->producerManageService->getSegmentTaskDetailList($param['param']);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取环节返修统计
     * @param Request $request
     * @return Response
     */
    public function getSegmentRepairCount(Request $request)
    {
        $param = $request->param();
        try {
            $resData = $this->producerManageService->getSegmentRepairCount($param['param']);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取环节返修工序详细列表
     * @param Request $request
     * @return Response
     */
    public function getSegmentRepairDetailList(Request $request)
    {
        $param = $request->param();
        try {
            $resData = $this->producerManageService->getSegmentRepairDetailList($param['param']);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取环节工单列表
     * @param Request $request
     * @return Response
     */
    public function getSegmentWorkOrderList(Request $request)
    {
        $param = $request->param();
        try {
            // 未处理工单的筛选
            if (!empty($param['param']['wait_handle_filter']) && $param['param']['wait_handle_filter'] == 'yes') {
                $validator = new ProducerManage();
                $validator->scene("WaitHandleFilter");
                if (!$validator->check($param)) {
                    throw_strack_exception($validator->getError(), ErrorCode::REQUEST_PARAM_ERROR);
                }
            }

            $resData = TaskWorkOrderService::getInstance()->list($param['param'], $request->getUserId(), $request->getTenantId());
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 任务列表
     * @param Request $request
     * @return Response
     * @throws \Exception
     */
    public function taskList(Request $request)
    {
        $param = $request->param();
        try {
            if (!empty($param['param']['filter']['history']) && $param['param']['filter']['history'] == 'yes') {
                $param['param']['filter']['time_search_type'] = 'history_' . $param['param']['filter']['time_search_type'];
            }
            if (false) { // TODO 是否可以移除
                $startTime = $param['param']['filter']['time_search'][0] ?? 0;
                $endTime = $param['param']['filter']['time_search'][1] ?? 0;

                $todoStepCategoryIdListFilter = $param['param']['filter']['todo_step_category_id'] ?? $param['param']['filter']['todo_step_category_id_list'] ?? [];
                $departmentId = $param['param']['filter']['department_id_user_filter'] ?? 0;


                $userId = $request->userId;
                if (!empty($departmentId)) {
                    $todoStepCategoryIdListFilter = [];

                    $du = TenantService::getInstance()->selectDepartmentUser(request()->getTenantId(), [
                        'param' => [
                            'filter' => [
                                'department_id' => $departmentId,
                            ]
                        ]
                    ]);
                    $saasUserIdList = array_column($du['rows'], 'saas_user_id');
                    if (!empty($saasUserIdList)) {
                        $userId = ["IN", $saasUserIdList];
                    }
                }
                if (!empty($todoStepCategoryIdListFilter)) {
                    $userId = 0;
                }

                $resData = ProducerManageHistoryService::getInstance()->historyTaskList(
                    $todoStepCategoryIdListFilter,
                    $param['param']['filter']['task.project_id'] ?? 0,
                    $userId,
                    $startTime,
                    $endTime,
                    $param['param']['filter']['time_search_type'] ?? 'delivery',
                    $param['param']['page'] ?? [1, C('default_page_total')]
                );
                return json(success_response('', $resData));
            }
            $resData = $this->producerManageService->taskList($param['param'], $request->getTenantId(), [], true);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 总进度任务详情统计
     * @param Request $request
     * @return Response
     */
    public function totalTaskCount(Request $request)
    {
        $param = $request->param();
        try {
            $resData = $this->producerManageService->totalTaskCount($param['param'], $request->tenantId);
            return json(success_response('', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 今日异常任务
     * @param \think\Request $request
     * @return \think\Response
     */
    public function todayAbnormalTask(Request $request)
    {
        $param = $request->param()['param'];
        if (isset($param['step_category_id']) && is_string($param['step_category_id'])) {
            $param['step_category_id'] = explode(",", $param['step_category_id']);
        }
        $resData = $this->producerManageService->todayAbnormalTask($param, $request->userId);
        return json(success_response('', $resData));
    }

}